package com.kate.mall.gateway.filter;

import com.kate.mall.log.constants.TraceConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * @Description: 全链路请求过滤器(发放traceId)
 * @Auther: 新梦想*陈超
 * @Date: 2022/1/27 16:32
 */
@Component
@Slf4j
public class RequestStatFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = MDC.get(TraceConstant.LOG_B3_TRACEID);
        MDC.put(TraceConstant.LOG_TRACE_ID, traceId);
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        log.info("request url = " + uri + ", traceId = " + traceId);
        request = exchange.getRequest().mutate().header(TraceConstant.HTTP_HEADER_TRACE_ID, traceId).build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
